package com.shijiwei.trip.task;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by sjw on 2015/12/11.
 */
public class ImageUtils extends AsyncTask<String,Void,ByteArrayOutputStream> {

    private ImageView imageView;

    public ImageUtils(ImageView imageView) {
        this.imageView = imageView;
    }

    @Override
    protected ByteArrayOutputStream doInBackground(String... params) {
        Bitmap bitmap = null;
        HttpURLConnection connection = null;
        URL url = null;
        ByteArrayOutputStream bos = null;
        try{
            url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            bos = new ByteArrayOutputStream();
            bitmap = BitmapFactory.decodeStream(bis);
            byte[] bytes = new byte[1024];
            int len;
            while( (len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (connection !=  null){
                connection.disconnect();
            }
        }
        return bos;
    }

    @Override
    protected void onPostExecute(ByteArrayOutputStream bos) {
        Bitmap bitmap = scaleImage(bos);
        imageView.setImageBitmap(bitmap);
    }

    public Bitmap scaleImage(ByteArrayOutputStream bos){
        BitmapFactory.Options  options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bos.toByteArray(),0,bos.toByteArray().length,options);

        int maxHight = 400;
        int maxWidth = 400;
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        int sampleSize = 1;
        while ((outHeight / sampleSize) > maxHight || (outWidth / sampleSize) > maxWidth) {
            sampleSize *= 2;
        }
        options.inSampleSize = sampleSize;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(bos.toByteArray(),0,bos.toByteArray().length,options);
    }
}
